package com.kinoshita.manager.config;

import org.springframework.amqp.core.AmqpAdmin;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.Binding.DestinationType;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.validation.constraints.NotNull;


@Configuration
public class RabbiMQConfig {

  @Value("${ads.publish.exchange:publishExchange}")
  private String adsPublishExchange;
  @Value("${ads.publish.routkey:routkey}")
  private String adsPublishRoutKey;
  @Value("${ads.publish.queue:publishQueue}")
  private String adsPublishQueue;

  @Resource
  @NotNull
  private AmqpAdmin amqpAdmin;

  @PostConstruct
  public void start() {
    amqpAdmin.declareExchange(new DirectExchange(adsPublishExchange, true, false));
    amqpAdmin.declareQueue(new Queue(adsPublishQueue, true));
    amqpAdmin.declareBinding(
        new Binding(adsPublishQueue, DestinationType.QUEUE, adsPublishExchange, adsPublishRoutKey,
            null
        ));

  }

  @Bean
  public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory) {
    RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
    rabbitTemplate.setMessageConverter(producerJackson2MessageConverter());
    return rabbitTemplate;
  }

  /**
   * 消息Json类型转换器
   *
   * @return
   */
  @Bean
  public Jackson2JsonMessageConverter producerJackson2MessageConverter() {
    return new Jackson2JsonMessageConverter();
  }

}
